package com.example.loginmvvm.musicList

import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import com.example.loginmvvm.lifecycle.AbsLifecycle
import com.example.loginmvvm.lifecycle.ILifecycle
import com.example.loginmvvm.lifecycle.ILifecycleOwner
import com.example.loginmvvm.lifecycle.LifeState
import com.example.loginmvvm.player.DataListenContainer
import com.example.loginmvvm.player.domain.Music

/*
 * class title: 
 * Author by RenChunLin, Email 18957806320@163.com, Date on 2021/4/19.
 * PS: Not easy to write code, please indicate.
 */
class MusicPresenter(owner: LifecycleOwner) {

    private val viewLifeImpl by lazy {
        ViewLifeImpl()
    }

    init {
        owner.lifecycle.addObserver(viewLifeImpl)
    }

    enum class MusicListLoadState {
        LOADING, EMPTY, SUCCESS, ERROR
    }

    private val musicModel by lazy {
        MusicModel()
    }

    /**
     * 音乐列表
     */
    val liveMusicList = MutableLiveData<List<Music>>()
    val musicList = DataListenContainer<List<Music>>()
    val loadState = DataListenContainer<MusicListLoadState>()

    private val page = 1
    private val size = 30

    fun getMusic() {
        loadState.value = MusicListLoadState.LOADING
        //从model层中获取音乐 列表
        musicModel.loadMusicByPage(page, size, object : MusicModel.OnMusicLoadResult {
            override fun onSuccess(result: List<Music>) {
                liveMusicList.postValue(result)
                musicList.value = result
                loadState.value = if (result.isEmpty()) {
                    MusicListLoadState.EMPTY
                } else {
                    MusicListLoadState.SUCCESS
                }
            }

            override fun onError(msg: String, code: Int) {
                loadState.value = MusicListLoadState.ERROR
                println("error...$msg...$code")
            }
        })
    }

    inner class ViewLifeImpl : LifecycleEventObserver {

        override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
            when (event) {
                Lifecycle.Event.ON_START -> {
                    //监听GPS信号变化
                    println("监听GPS信号变化ON_START")
                }

                Lifecycle.Event.ON_PAUSE -> {
                    //监听GPS信号变化
                    println("监听GPS信号变化ON_PAUSE")
                }
            }
        }
    }
}